package com.itheima.mobile.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.common.entity.Result;
import com.itheima.mobile.dto.OrderDto;
import com.itheima.mobile.mapper.MemberDao;
import com.itheima.mobile.pojo.Member;
import com.itheima.mobile.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Service
public class IMemberServiceImpl implements IMemberService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberDao memberDao;

    /**
     * 用户登录
     *
     * @param orderDto 存放电话号码，验证码
     */
    @Override
    public Result login(OrderDto orderDto, HttpServletResponse response) {

        if (orderDto.getTelephone() == null || orderDto.getTelephone().equals("")) {
            return Result.of(false, "电话不能为空!", null);
        }

        if (orderDto.getValidateCode() == null || orderDto.getValidateCode().equals("")) {
            return Result.of(false, "验证码不能为空!", null);
        }

        //校验验证码
        String validateCode = redisTemplate.opsForValue().get(orderDto.getTelephone());

        if (!orderDto.getValidateCode().equals(validateCode)) {
            return Result.of(false, "验证码错误!", null);
        }

        //检查当前用户如不是会员，需要自动完成注册
        Member member = memberDao.getMemberByPhone(orderDto.getTelephone());
        if (member == null) {
            //不是会员，自动注册
            member = new Member();
            member.setName(orderDto.getTelephone());
            member.setPhoneNumber(orderDto.getTelephone());
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //将电话存入cookie
        Cookie cookie = new Cookie("phone",orderDto.getTelephone());
        response.addCookie(cookie);


        //将会员信息存入redis
        redisTemplate.opsForValue().set("memberInfo_"+orderDto.getTelephone(), JSON.toJSONString(member));


        return Result.of(true, "登录成功!", null);
    }
}
